﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;

namespace FYPHP
{
    public partial class SearchAdvanced : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["fyphp"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            MultiView1.ActiveViewIndex = -1;
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            SqlCommand cmdProduct;
            SqlDataReader dtrProduct;
            conn.Open();

            if (txtName.Text == "" && txtDesc.Text == "" && txtSeller.Text == "" && txtFrom.Text == "" && txtTo.Text == "")
            {
                MultiView1.ActiveViewIndex = 1;
            }
            else
            {
                String query = "SELECT * FROM Products p, Users u WHERE p.u_id=u.u_id";

                if (txtName.Text != "")
                    query += " AND p_name LIKE '%" + txtName.Text + "%'";

                if (txtDesc.Text != "")
                    query += " AND p_desc LIKE '%" + txtDesc.Text + "%'";

                if (txtSeller.Text != "")
                    query += " AND username ='" + txtSeller.Text + "'";

                if (txtFrom.Text != "")
                    query += " AND p_price >='" + txtFrom.Text + "'";

                if (txtTo.Text != "")
                    query += " AND p_price <='" + txtTo.Text + "'";

                query += " AND p_category ='" + DropDownList1.SelectedValue + "'";

                cmdProduct = new SqlCommand(query, conn);
                int num = Convert.ToInt32(cmdProduct.ExecuteScalar());

                if (num != 0)
                {
                    dtrProduct = cmdProduct.ExecuteReader();

                    ItemList.DataSource = dtrProduct;
                    ItemList.DataBind();
                    dtrProduct.Close();

                    MultiView1.ActiveViewIndex = 0;
                }
                else
                {
                    MultiView1.ActiveViewIndex = 1;
                }

                conn.Close();
            }
        }

        private void MessageBox(string msg)
        {
            Label lbl = new Label();
            lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
            Page.Controls.Add(lbl);
        }
    }
}